<?php

namespace App\Http\Controllers\backend;

use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Input;
use App\Models\Member;
use Illuminate\Support\Facades\Hash;

class MemberController extends BaseController {
	
	public function index() {
		$members = Member::paginate(20);
		return view('backend.members', compact('members'));
	}
	
	public function create() {
		$member = new Member();
		return view('backend.member_form', compact('member'));
	}
	
	public function store() {
		$input = Input::all();
		$avatar = $input['avatar'];
		unset($input['avatar']);
		$validation = validator($input, Member::$rules, Member::$msgs);
		if($validation->passes()) {
			$input['password'] = Hash::make($input['password']);
			$member = Member::create($input);
			$avatar->move(public_path('uploads/images'), $member->id.'.jpg');
			$avatar = $member->id.'.jpg';
			$member->avatar = $avatar;
			$member->save();
			return redirect('backend/members');
		}
		return Redirect::back()
				->withInput()
				->withErrors($validation);
	}
	
	public function edit($id) {
		$member = Member::find($id);
		return view('backend.member_form', compact('member'));
	}
	
	public function update($id) {
		$input = Input::all();
		$member = Member::find($id);
		$rules = [
			'nickname' => 'required',
			'cellphone' => 'required',
		];
		if(empty($input['password'])) {
			unset($input['password']);
		}
		$validation = validator($input, $rules, Member::$msgs);
		if($validation->passes()) {
			if(isset($input['avatar'])) {
				if($member->avatar != 'nocover.jpg') {
					@unlink(public_path('uploads/images/'. $member->avatar ));
				}
				$input['avatar']->move(public_path('uploads/images'), $member->id.'.jpg');
				$input['avatar'] = $member->id.'.jpg';
			}
			$member->update($input);
			$member->save();
			return redirect('backend/members');
		}
		return Redirect::back()
				->withInput()
				->withErrors($validation);
	}
	
	public function destroy($id) {
		$member = Member::find($id);
		if($member->avatar != 'nocover.jpg') {
			@unlink(public_path('uploads/avatar/'. $member->avatar ));
		}
		$member->delete();
		return redirect('backend/members');
	}
}
